<?php
/**
 * ComProductsDao.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/10/27- 11:02 上午
 */
namespace common\dao;
use common\exception\ValidatorException;
use common\library\BaseDao;
use common\models\com\ComProducts;
use common\constants\BaseConst;


class ComProductsDao extends BaseDao
{


    /**
     * 写入商品表信息
     * @param array $data
     * @return ComProducts
     * @throws ValidatorException
     */
    public function saveData(array $data):ComProducts
    {

        if(!isset($data['platform']) || !isset($data['num_iid'])) throw new ValidatorException('参数缺失');

        $product = new ComProducts();

        $productSet = ComProducts::findOne(['platform'=>$data['platform'],'num_iid'=>$data['num_iid'],'uid'=>$data['uid'],'is_delete' => BaseConst::UNDELETED]);

        /**
         * 存在更新操作
         */
        if($productSet)
        {
            $product = $productSet;
        }


        $product->load($data,'');

        if (!$product->validate()) {
            throw new ValidatorException($product->errorsToString());
        }

        if($product->save())
        {
            return $product;
        }else{
            throw new ValidatorException($product->errorsToOneString());
        }
    }


    /**
     * 通过主键获取信息
     * @param int $id
     * @return ComProducts
     */
    public function getByPk(int $id):ComProducts
    {
        return ComProducts::findOne(['id'=>$id]);
    }


    /**
     * 获取指定平台服务，指定用户，指定平台，指定唯一主键的商品信息
     * @param $server
     * @param $uid
     * @param $platform
     * @param $uuid
     * @return ComProducts|null
     */
    public function getByServerAndUidAndPlatformAndUUID($server,$uid,$platform,$uuid)
    {
        return ComProducts::findOne([
            'server_id'=>$server,
            'uid' => $uid,
            'platform' => $platform,
            'num_iid' => $uuid
        ]);
    }



}